package com.imooc.reader.controller.management;

import com.imooc.reader.entity.Book;
import com.imooc.reader.service.BookService;
import com.imooc.reader.service.Exception.BussinessException;
import com.jhlabs.image.MutatableFilter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/management/book")
@Controller
public class MBookController {

    @Autowired
    private BookService bookService;

    @GetMapping("/index.html")
    public ModelAndView show() {
        return new ModelAndView("/mangagement/book");
    }

    @PostMapping("/upload")
    @ResponseBody
    public Map upload(@RequestParam("img") MultipartFile file, HttpServletRequest request) throws IOException {
        String s = request.getServletContext().getResource("/").getPath() + "/upload/";
        //文件名
        String fileName = new SimpleDateFormat("yyMMddHHmmssSSS").format(new Date());
        //获取源文件的后缀名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //保存文件到自己的文件夹里
        file.transferTo(new File(s + fileName + suffix));
        HashMap result = new HashMap();
        result.put("errno", 0);
        result.put("data", new String[]{"/upload/" + fileName + suffix});
        return result;
    }


    //新增图书
    @PostMapping("/create")
    @ResponseBody
    public Map creatBook(Book book) {
        Map result = new HashMap();
        try {


            book.setEvaluationQuantity(0);
            book.setEvaluationScore(0f);
            Document doc = Jsoup.parse(book.getDescription());
            Element img = doc.select("img").first();
            String src = img.attr("src");
            book.setCover(src);
            bookService.creatBook(book);
            result.put("code", "0");
            result.put("msg", "success");

        } catch (BussinessException e) {
            e.printStackTrace();
            result.put("code", e.getCode());
            result.put("msg", e.getMessage());
        }
        return result;

    }
}
